//
//  CarContrastConsequenceViewModel.m
//  CarUser
//
//  Created by ayi on 2019/1/23.
//  Copyright © 2019 王森林. All rights reserved.
//



#import "CarContrastConsequenceViewModel.h"

#import <YYCategories/UIScrollView+YYAdd.h>
#import <YYCategories/UITableView+YYAdd.h>

#import "CarImgModel.h"
#import "CarDetailInfoModel.h"
#import "CarConfigurationModel.h"
#import "CarCommentModel.h"
#import "CarSaleCarListModel.h"
#import "CarDetailBaseModel.h"

#import "Car_ContrastConsequenceHeaderTableViewCell.h"
#import "Car_ContrastConsequenceCell.h"



@interface CarContrastConsequenceViewModel()

@property (nonatomic, strong) CarDetailMainModel *model1;
@property (nonatomic, strong) CarDetailMainModel *model2;

@property (nonatomic, assign) BOOL ishidden;

@end

@implementation CarContrastConsequenceViewModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)resetListAry:(NSArray *)listAry{
    self.model1 = listAry.firstObject;
    self.model2 = listAry.lastObject;
    
    UIView *header = objc_getAssociatedObject(self.childvc, @"header");
    if (header == nil) {
        Car_ContrastConsequenceHeaderTableViewCell *cell = [Car_ContrastConsequenceHeaderTableViewCell initCellWithReuseIdentifier:@"Car_ContrastConsequenceHeaderTableViewCellHeader" andTab:self.childtab];
        cell.lab1.text = self.model1.cardetailInfoModel.CXMC00;
        cell.moneyLab1.text = [NSString stringWithFormat:@"￥%@万",self.model1.cardetailInfoModel.ZDJG00];
        cell.lab2.text = self.model2.cardetailInfoModel.CXMC00;
        cell.moneyLab2.text = [NSString stringWithFormat:@"￥%@万",self.model2.cardetailInfoModel.ZDJG00];
        [self.childvc.view addSubview:cell.contentView];
        objc_setAssociatedObject(self.childvc, @"header", cell.contentView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        cell.contentView.frame = CGRectMake(0, 0, BOUNDWIDTH, 90);
        cell.contentView.backgroundColor = UIColor.whiteColor;
        
        [cell.hiddenBtn addTarget:self action:@selector(hiddenBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    
    
    [self.listAry removeAllObjects];
    //头部
//    CarConsequenceModel *model = [[CarConsequenceModel alloc]init];
//    model.type = Consequence_CellType_Header;
//    [self.listAry addObject:model];
    
    //基本参数
    [self resetListCellLabWithTtitle:@"基本参数"];
    
    //舒适配置
    [self resetListWithTitle:@"舒适配置" andLeftAry:self.model1.ssList andRightAry:self.model2.ssList];
    //安全配置
    [self resetListWithTitle:@"安全配置" andLeftAry:self.model1.aqList andRightAry:self.model2.aqList];
    //操控配置
    [self resetListWithTitle:@"操控配置" andLeftAry:self.model1.ckList andRightAry:self.model2.ckList];
    
    [self.childtab reloadData];
}
//基本参数
- (void)resetListCellLabWithTtitle:(NSString *)title{
    CarConsequenceModel *model2 = [[CarConsequenceModel alloc]init];
    model2.title = title;
    model2.type = Consequence_CellType_Cell_Lab;
    
    /*
     GGBBMC：规格版本,
     JBMC00：级别
     JGMC00：结构,
     CKG000：长*宽* 高
     CSJGMC：车身结构,
     BSXJC0：变速箱简称
     RLMC00：燃料,
     JQFSMC：进气方式,
     QDMC00：驱动,
     ML0000：马力,
     ZDGL00：最大功率,
     ZDNJ00：最大扭矩,
     ZGCS00：最高车速,
     ZHYH00：综合油耗,
     */
    
    //规格版本
    [self resetListCellLabChildWithTtitle:@"规格版本" andLeft:_model1.cardetailInfoModel.GGBBMC andRight:_model2.cardetailInfoModel.GGBBMC withModel:model2];
    [self resetListCellLabChildWithTtitle:@"级别" andLeft:_model1.cardetailInfoModel.JBMC00 andRight:_model2.cardetailInfoModel.JBMC00 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"结构" andLeft:_model1.cardetailInfoModel.JGMC00 andRight:_model2.cardetailInfoModel.JGMC00 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"长*宽*高" andLeft:_model1.cardetailInfoModel.CKG000 andRight:_model2.cardetailInfoModel.CKG000 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"车身结构" andLeft:_model1.cardetailInfoModel.CSJGMC andRight:_model2.cardetailInfoModel.CSJGMC withModel:model2];
    [self resetListCellLabChildWithTtitle:@"变速箱简称" andLeft:_model1.cardetailInfoModel.BSXJC0 andRight:_model2.cardetailInfoModel.BSXJC0 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"燃料" andLeft:_model1.cardetailInfoModel.RLMC00 andRight:_model2.cardetailInfoModel.RLMC00 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"进气方式" andLeft:_model1.cardetailInfoModel.JQFSMC andRight:_model2.cardetailInfoModel.JQFSMC withModel:model2];
    [self resetListCellLabChildWithTtitle:@"驱动" andLeft:_model1.cardetailInfoModel.QDMC00 andRight:_model2.cardetailInfoModel.QDMC00 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"马力" andLeft:_model1.cardetailInfoModel.ML0000 andRight:_model2.cardetailInfoModel.ML0000 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"最大功率" andLeft:_model1.cardetailInfoModel.ZDGL00 andRight:_model2.cardetailInfoModel.ZDGL00 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"最大扭矩" andLeft:_model1.cardetailInfoModel.ZDNJ00 andRight:_model2.cardetailInfoModel.ZDNJ00 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"最高车速" andLeft:_model1.cardetailInfoModel.ZGCS00 andRight:_model2.cardetailInfoModel.ZGCS00 withModel:model2];
    [self resetListCellLabChildWithTtitle:@"综合油耗" andLeft:_model1.cardetailInfoModel.ZHYH00 andRight:_model2.cardetailInfoModel.ZHYH00 withModel:model2];
    
    
    [self.listAry addObject:model2];
}

- (void)resetListCellLabChildWithTtitle:(NSString *)title andLeft:(NSString *)leftStr andRight:(NSString *)rightStr withModel:(CarConsequenceModel *)model{
    CarConsequenceChildModel *child2 = [[CarConsequenceChildModel alloc]init];
    child2.title = title;
    child2.customTitle1 =  leftStr;
    child2.customTitle2 =  rightStr;
    child2.type = model.type;
    [model.childModelList addObject:child2];
    
    if ([leftStr isEqualToString:rightStr]) {
        
        [model.childModelHiddenList addObject:child2];
        child2.anchorIndex = [model.childModelList indexOfObject:child2];
    }
}

//配置
- (void)resetListWithTitle:(NSString *)title andLeftAry:(NSMutableArray *)leftAry andRightAry:(NSMutableArray *)rightAry{
    CarConsequenceModel *model = [[CarConsequenceModel alloc]init];
    model.title = title;
    model.type = Consequence_CellType_Cell;
    
    NSMutableArray *ary = [NSMutableArray arrayWithCapacity:0];
    [ary addObjectsFromArray:leftAry];
    [ary addObjectsFromArray:rightAry];
    NSArray *uniconidAry = [ary valueForKeyPath:@"@distinctUnionOfObjects.DICTIONARIES_ID"];
    
    [uniconidAry enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"DICTIONARIES_ID='%@'",obj]];
        CarConfigurationModel *model1 = [leftAry filteredArrayUsingPredicate:predicate].firstObject;
        CarConfigurationModel *model2 = [rightAry filteredArrayUsingPredicate:predicate].firstObject;
        
        if (model1 != nil || model2 != nil) {
            CarConsequenceChildModel *childmodel = [[CarConsequenceChildModel alloc]init];
            childmodel.title = model1?model1.NAME : model2.NAME;
            childmodel.leftModel = model1;
            childmodel.rightModel = model2;
            childmodel.type = model.type;
            [model.childModelList addObject:childmodel];
            if (model1 != nil && model2 != nil) {
                [model.childModelHiddenList addObject:childmodel];
                childmodel.anchorIndex = idx;
            }
        }
    }];
    if (model.childModelList.count > 0) {
         [self.listAry addObject:model];
    }
}

- (void)addAnchorList{
    [self.listAry enumerateObjectsUsingBlock:^(CarConsequenceModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.childModelHiddenList enumerateObjectsUsingBlock:^(CarConsequenceChildModel * _Nonnull childobj, NSUInteger childidx, BOOL * _Nonnull childstop) {
            if ([obj.childModelList indexOfObject:childobj] == NSNotFound) {
                [obj.childModelList insertObject:childobj atIndex:childobj.anchorIndex];
            }
        }];
    }];
    
    [self.childtab reloadData];
}

- (void)removeAnchorList{
    @weakify(self);
    [self.listAry enumerateObjectsUsingBlock:^(CarConsequenceModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        @strongify(self);
        NSMutableArray *rowAry = [obj.childModelHiddenList valueForKeyPath:@"@unionOfObjects.anchorIndex"];
        NSInteger oldcount = obj.childModelList.count;
        [obj.childModelHiddenList enumerateObjectsUsingBlock:^(CarConsequenceChildModel * _Nonnull childobj, NSUInteger childidx, BOOL * _Nonnull childstop) {
            [obj.childModelList removeObject:childobj];
        }];
        
        [self.childtab updateWithBlock:^(UITableView * _Nonnull tableView) {
            [rowAry enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSNumber *rowobj, NSUInteger rowidx, BOOL * _Nonnull rowistop) {
                if (rowobj.integerValue < oldcount) {
                    [self.childtab deleteRow:rowobj.integerValue inSection:idx withRowAnimation:UITableViewRowAnimationTop];
                }
            }];
        }];
        
    }];

}


#pragma mark ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------按钮事件
- (void)hiddenBtnAction:(UIButton *)btn{
    btn.selected = !btn.selected;
    self.ishidden = btn.selected;
    
    if (self.ishidden) {
        [self removeAnchorList];
    }else{
        [self addAnchorList];
    }
    
}






#pragma mark ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.listAry.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    CarConsequenceModel *model = self.listAry[section];
    switch (model.type) {
        case Consequence_CellType_Header:
            return 1;
        default:
             return model.childModelList.count;
            break;
    }
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CarConsequenceModel *model = self.listAry[indexPath.section];
    CarConsequenceChildModel *childmodel = model.childModelList[indexPath.row];
    Car_ContrastConsequenceCell *cell = [Car_ContrastConsequenceCell initCellWithReuseIdentifier:@"Car_ContrastConsequenceCell" andTab:tableView];
    cell.childmodel = childmodel;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}




#pragma mark ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CarConsequenceModel *model = self.listAry[indexPath.section];
//    CarConsequenceChildModel *childmodel = model.childModelList[indexPath.row];
    switch (model.type) {
        case Consequence_CellType_Header:
            return 100;
            break;
        default:
            return 50;
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CarConsequenceModel *model = self.listAry[section];
    if (self.ishidden) {
        if (model.childModelList.count == 0) {
            return [UIView new];
        }
    }
    UIView *header = [[UIView alloc]init];header.backgroundColor = Common_BackgroundGrayColor;
    UILabel *titleLab = [UILabel customInitLabWithFont:12 andTextColor:Common_TextColor andAlign:NSTextAlignmentCenter];
    UILabel *rightLab = [UILabel customInitLabWithFont:12 andTextColor:Common_TextColor andAlign:NSTextAlignmentRight];
    [header addSubview:titleLab];
    [header addSubview:rightLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        (void)make.centerY;
        (void)make.left;
        make.width.mas_equalTo(BOUNDWIDTH * 1/5);
        make.height.mas_equalTo(ceilf(titleLab.font.lineHeight));
    }];
    [rightLab mas_makeConstraints:^(MASConstraintMaker *make) {
        (void)make.centerY;
        make.right.mas_equalTo(-15);
        make.left.equalTo(titleLab.mas_right).offset(10);
        make.height.mas_equalTo(ceilf(titleLab.font.lineHeight));
    }];
    
    
    
    titleLab.text = model.title;
//    rightLab.attributedText = [self tipsRightAttributeStr];
    
    return header;
//    UIView *header = [[UIView alloc]init];header.backgroundColor = self.sectionHeaderColor?:[UIColor whiteColor];
//    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc]init];footer.backgroundColor = self.sectionFooterColor?:[UIColor whiteColor];
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CarConsequenceModel *model = self.listAry[section];
    if (self.ishidden) {
        if (model.childModelList.count == 0) {
            return 0;
        }
    }
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}


- (NSMutableAttributedString *)tipsRightAttributeStr{
    NSMutableDictionary *attributesParams = @{NSFontAttributeName:FONT_SIZE(12),
                                              NSForegroundColorAttributeName:Common_TextColor
                                              }.mutableCopy;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"标配    准配    - 无" attributes:attributesParams];
    NSTextAttachment *attachImg1 = [[NSTextAttachment alloc]init];
    attachImg1.image = IMG(@"point_default");
    attachImg1.bounds = CGRectMake(0, -2, 14, 14);
    NSTextAttachment *attachImg2 = [[NSTextAttachment alloc]init];
    attachImg2.image = IMG(@"point_null");
    attachImg2.bounds = CGRectMake(0, -2, 14, 14);
    NSAttributedString *imgStr1 = [NSAttributedString attributedStringWithAttachment:attachImg1];
    NSAttributedString *imgStr2 = [NSAttributedString attributedStringWithAttachment:attachImg2];
    [str insertAttributedString:imgStr1 atIndex:0];
    [str insertAttributedString:imgStr2 atIndex:7];
    return str;
}




@end








@implementation CarConsequenceModel

- (NSMutableArray<CarConsequenceChildModel *> *)childModelList{
    if (!_childModelList) {
        _childModelList = [NSMutableArray arrayWithCapacity:0];
    }
    return _childModelList;
}

- (NSMutableArray<CarConsequenceChildModel *> *)childModelHiddenList{
    if (!_childModelHiddenList) {
        _childModelHiddenList = [NSMutableArray arrayWithCapacity:0];
    }
    return _childModelHiddenList;
}



@end



@implementation CarConsequenceChildModel



@end
